package com.wsx.ones.monitor.core.exec;

import com.wsx.ones.monitor.common.util.FinalStaticUtil;
import com.wsx.ones.monitor.core.model.RpcRequest;
import com.wsx.ones.monitor.core.model.RpcResponse;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 客户端操作结果的回调
 * 主要是获得服务端的结果
 * Created by wangshuaixin on 17/2/6.
 */
public class PushCallback {

    private RpcRequest rpcRequest;
    private RpcResponse rpcResponse;

    private ReentrantLock lock = new ReentrantLock();
    private Condition finish = lock.newCondition();

    public PushCallback(RpcRequest rpcRequest) {
        this.rpcRequest = rpcRequest;
    }

    /**
     * 客户端的发送操作
     * @return
     * @throws InterruptedException
     */
    public Object doBegin() throws InterruptedException {
        try {
            lock.lock();
            finish.await(FinalStaticUtil.PUSH_SLEEP_TIME, TimeUnit.MILLISECONDS);
            if (null != rpcResponse) {
                return rpcResponse.getResultVal();
            }
            return null;
        } finally {
            lock.unlock();
        }
    }

    /**
     * 客户端的接受操作
     * @param rpcResponse
     */
    public void doEnd(RpcResponse rpcResponse) {
        try {
            lock.lock();
            this.rpcResponse = rpcResponse;
            finish.signal();
        } finally {
            lock.unlock();
        }
    }
}
